﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Edge.Business.Domain.Application;
using Edge.Business.Entities;
using Edge.Common.ComponentModel.Notification;
using Edge.Common.Services;
using Edge.Common.Utils;
using Shop.Business.Domain.Catalog;
using Shop.Business.Domain.Customers;
using Shop.Business.Domain.Orders;
using Shop.Business.Domain.Orders.Logic;

namespace Shop.Web.AppCode
{
    public class ShopBasePage : Page
    {

          string defaultTitle = "Детская одежда, обувь и аксессуары от волшебников. Интернет-магазин детской одежды \"Морлин\".";

//        public static TmpOrder GetCurrentOrder()
//        {
//            if (CurrentCustomer != null)
//            {
//                return Locator.GetService<IOrderManager>().GetDraftOrder(CurrentCustomer);
//            }
//            if (Locator.GetService<IContextObjects>().Get<OrderHolder>() == null)
//            {
//                TmpOrder order = new TmpOrder();
//                order.OrderStatus = OrderStatus.Draft;
//                Locator.GetService<IContextObjects>().Set<OrderHolder>(new OrderHolder(order));
//                return Locator.GetService<IContextObjects>().Get<OrderHolder>().Object;
//            }
//            return Locator.GetService<IContextObjects>().Get<OrderHolder>().Object;
//        }

//        public static void SetCurrentOrder(TmpOrder value)
//        {
//            if (value.OrderStatus == OrderStatus.Draft)
//                if (CurrentCustomer != null)
//                {
//                    Locator.GetService<IOrderManager>().Save(value);
//                }
//                else
//                {
//                    Locator.GetService<IContextObjects>().Set<OrderHolder>(new OrderHolder(value));
//                }
//        }

        public const string NoImage = "~/images/Default/no-image.jpg";
        public const string ReturnUrl = "http://localhost/Shop/VK.aspx";
        public const string AuthUrl = "http://api.vkontakte.ru/oauth/authorize";
        public const string TokenUrl = "https://api.vkontakte.ru/oauth/access_token";

        public static string GetImagePath(BaseEntity<int> obj)
        {
            string subFolder = String.Empty;
            if (obj as Brand != null)
                subFolder = "Brand";
            else if (obj as Business.Domain.Catalog.Product != null)
                subFolder = "Product";
            string path = HttpContext.Current.Server.MapPath("images") + "\\" + subFolder+ "\\" + string.Format("thumb_IMG{0}.jpg", obj.Id);
            if (File.Exists(path))
                return "images\\" + subFolder + "\\" + string.Format("thumb_IMG{0}.jpg", obj.Id);
            return NoImage;
        }

        public void AccessDeniedMessage()
        {
            //Locator.GetService<INotificationManager>().Error("У вас нет прав для просмотра данной страницы");
            Response.Redirect("~/Default.aspx");
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            bool Update = Convert.ToBoolean(ConfigurationManager.AppSettings["Update"]);
            if (Update)
            {
                AccessDeniedMessage();
            }
            else
            {

                if (Locator.GetService<IContextObjects>().Get<CustomerHolder>() == null)
                {
                    Customer cc = null;
                    string AutoLogin = System.Configuration.ConfigurationManager.AppSettings["AutoLogin"];
                    if (!StringUtils.IsEmptyOrNull(AutoLogin))
                        cc = Locator.GetService<ICustomerManager>().Load(Convert.ToInt32(AutoLogin));
                    string CookieName = ConfigurationManager.AppSettings["CookieName"];
                    if (cc == null && !StringUtils.IsEmptyOrNull(CookieName) && Request.Cookies[CookieName] != null && !StringUtils.IsEmptyOrNull(Request.Cookies[CookieName].Value.ToString()))
                    {
                        cc = Locator.GetService<ICustomerManager>().Load(Convert.ToInt32(Request.Cookies[CookieName].Value));
                        try
                        {
                            if (cc != null)
                                if (!cc.RememberMe)
                                    cc = null;
                        }
                        catch (Exception)
                        {

                        }
                        
                    }
                    if (cc != null)
                    {
                        SetCustomerHolder(cc);
                    }
                }
                
            }
            SetTitle(defaultTitle);
        }

        protected void SetCustomerHolder(Customer customer)
        {
            Locator.GetService<IContextObjects>().Set<CustomerHolder>(new CustomerHolder(customer));
            string CookieName = ConfigurationManager.AppSettings["CookieName"];
            HttpCookie cookie = new HttpCookie(CookieName, customer.Id.ToString());
            cookie.Expires = DateTime.Now.AddMonths(6);
            Response.Cookies.Add(cookie);
            if (Session["Order"] != null && ((List<OrderItem>)Session["Order"]).Count > 0)
            {
                Order order = Locator.GetService<IOrderManager>().GetOrderWithStatus(customer, OrderStatus.Draft);
                OrderController controller = new OrderController(order);
                controller.MergeOrders((List<OrderItem>)Session["Order"]);
                ((List<OrderItem>)Session["Order"]).Clear();
            }

        }

        protected void SetTitle(string title)
        {
            if (Master != null)
            {
                Literal ltTitle = (Literal) Master.FindControl("ltTitle");
                if (ltTitle != null)
                {

                    if (title != defaultTitle)
                        ltTitle.Text = title + ". " + defaultTitle;
                    else
                        ltTitle.Text = defaultTitle;
                }
            }
        }


        protected void UnSetCustomerHolder()
        {
            Locator.GetService<IContextObjects>().Set<CustomerHolder>(null);
            string CookieName = ConfigurationManager.AppSettings["CookieName"];
            HttpCookie cookie = new HttpCookie(CookieName);
            cookie.Expires = DateTime.Now.AddDays(-1d);
            Response.Cookies.Add(cookie);
            if (Session["Order"] != null)
                ((List<OrderItem>)Session["Order"]).Clear();
        }
    }
}